package com.tang.netty.nio.client;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

@Slf4j
public class NioClient {

    public static void main(String[] args) throws IOException {
        // 1新建Selector
        Selector selector = Selector.open();
        // 2打开socketChannel
        SocketChannel socketChannel = SocketChannel.open();
        // 3设置通道为非阻塞
        socketChannel.configureBlocking(false);
        // 4链接服务器端
        boolean isConnect = socketChannel.connect(new InetSocketAddress("127.0.0.1",7397));
        // 5注册通道到selector
        if (isConnect) {
            socketChannel.register(selector, SelectionKey.OP_READ);
        } else {
            socketChannel.register(selector, SelectionKey.OP_CONNECT);
        }
        log.info("nio client start done!");
        // 6处理数据
        new NioClientHandler(selector, StandardCharsets.UTF_8).start();
    }

}
